<template>
	<view class="navbar">
		<view class="fixed-content" :class="showBack || top > 10 ? 'bg-b' : ''">
			<!-- 状态栏高度 -->
			<view :style="{'height': geStatusBarHeight() + 'px'}"></view>
			<!-- 导航栏高度 -->
			<view class="bar-content" :style="{'height': getNavBarHeight()+'px'}">
				<!-- <slot> -->
				<image v-if="showBack" @tap="navigateBack()" class="nav-left" src="/static/image/nav-back.png" mode="">
				</image>
				<view class="search-flex">
					<view class="search-area" @tap="clickFn">
						<image class="search-icon" src="../static/image/homePage/icon-search.png"></image>
						<uv-input class="search-input" placeholder="点击输入要查询的内容" v-model="keywords"
							:readonly="readonly"></uv-input>
						<view class="search-btn" @tap="searchFn">搜索</view>
					</view>
					<view class="operate-area">
						<image class="opt-btn" @click="checkAuth" src="../static/image/homePage/icon-scan.png"></image>
						<image class="opt-btn" @click="showCodeFn" src="../static/image/homePage/icon-edit.png"></image>
					</view>
				</view>
				<!-- </slot> -->
			</view>
		</view>
		<view class="list">
			<view class="item" v-for="item,i in list" :key="i" @click="jump(item.path)">
				{{item.key}}
			</view>
		</view>
		<view class="default" v-if="none">暂无内容</view>
		<!-- 占位高度，状态栏高度+导航栏高度，父组件就不需要计算导航栏高度 -->
		<view :style="{'height': geStatusBarHeight() + getNavBarHeight() + 'px'}"></view>

		<popPromptBox v-if="show" :msg="msg" @confirm="confirmFn" @close="show = false"></popPromptBox>
		<popCode v-if="showCodePop" @confirm="codeConfirm" @cancel="codeCancel"></popCode>

		<popPromptBox v-if="showLogin" msg="请登录" btnTxt="去登录" :showClose="true" @confirm="handleToLogin"
			@close="showLogin = false"></popPromptBox>

		<popPromptBox v-if="userInfoGuide" msg="请先完善个人信息" btnTxt="去完善" :showClose="true" @confirm="userInfoGuideConfirm"
			@close="userInfoGuideCancel"></popPromptBox>

		<!-- 扫一扫授权弹窗 -->
		<selectContentView v-if="confirmTipShow" :msg="confirmTipMsg" :confirmTitle="confirmTipConfirmText"
			:cancelTitle="confirmTipCancelText" @confirm="confirmTipConfirm" @cancel="confirmTipCancel">
		</selectContentView>
	</view>
</template>

<script>
	import popCode from './popCode.vue'
	import permision from "@/js_sdk/wa-permission/permission.js"
	export default {
		name: 'Search',
		props: {
			readonly: {
				type: Boolean
			},
			showBack: {
				type: Boolean,
				default: false
			},
			top: {
				type: Number
			}
		},
		components: {
			popCode
		},
		data() {
			return {
				showLogin: false,
				userInfoGuide: false,
				showCodePop: false,
				show: false,
				haveAuth: false, // 相机权限
				msg: '',
				keywords: '',
				keywordsList: [{
						key: '蜂竞技',
						path: '/pages/games/index',
						words: ['蜂竞技', '极速拼词', '字母接龙', '拼词竞技', '训练', '联机', '游戏', '竞技', '比赛']
					},
					{
						key: '蜂词典',
						path: '/pages/lexicon/lexIconHome',
						words: ['词库', '词典', '个人赛', '团体赛', 'SPBCN词库']
					},
					{
						key: '蜂计划',
						path: '/pages/planBee/planBeeHome',
						words: ['计划', '打卡', '学习', '生词本', '蜂计划']
					}
				],
				list: [],
				none: false,
				confirmTipShow: false,
				confirmTipMsg: '',
				confirmTipConfirmText: '',
				confirmTipCancelText: '',
			}
		},
		methods: {
			// 获取状态栏高度
			geStatusBarHeight() {
				return uni.getSystemInfoSync()['statusBarHeight']
			},
			// 获取导航栏高度
			getNavBarHeight() {
				// #ifdef MP-WEIXIN
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				// 导航栏高度 = 胶囊高度 + 上间距 + 下间距 + 微调	（menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight'] = 上间距）	        
				let navbarHeight = menuButtonInfo.height + (menuButtonInfo.top - uni.getSystemInfoSync()[
					'statusBarHeight']) * 2 + 2
				// #endif
				// #ifdef APP-PLUS || H5
				let navbarHeight = 44
				// #endif
				return navbarHeight
			},
			navigateBack() {
				uni.navigateBack()
			},
			clickFn() {
				const token = uni.getStorageSync('TOKEN_YX')
				if (!token) {
					uni.navigateTo({
						url: "/pages/login/login"
					})
				} else {
					if (this.readonly) {
						uni.navigateTo({
							url: "/pages/tabbar/home/search"
						})
					}
				}
			},
			searchFn() {
				if (this.readonly) return
				this.list = []
				this.keywordsList.forEach(item => {
					const res = item.words.filter(word => word.includes(this.keywords))
					// console.log(res)
					if (res.length) {
						this.list.push({
							path: item.path,
							key: `${item.key}-${res}`
						})
					}
				})
				console.log(this.list)

				this.none = !this.list.length
			},
			jump(path) {
				uni.navigateTo({
					url: path
				})
			},
			showCameraTip() {
				// 提示弹窗
				// this.msg = '扫一扫功能需要访问摄像头权限来识别二维码'
				// this.show = true
				this.confirmTipShow = true
				this.confirmTipMsg = '扫一扫识别二维码功能，需要访问您的摄像头权限、存储权限'
				this.confirmTipConfirmText = '同意'
				this.confirmTipCancelText = '拒绝'
			},
			confirmTipConfirm() {
				this.confirmTipShow = false
				this.scanFn()
				uni.setStorageSync('notFirstInScan', '1')
			},
			confirmTipCancel() {
				this.confirmTipShow = false
			},
			checkInfo() {
				const token = uni.getStorageSync('TOKEN_YX')
				const infoC = uni.getStorageSync('infoCompleted')
				console.log(token, infoC)
				if (!token) {
					this.showLogin = true
					return false
				} else if (infoC === '0') {
					// 弹窗提示完善信息
					this.userInfoGuide = true
					return false
				} else {
					return true
				}
			},
			handleToLogin() {
				this.showLogin = false
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			userInfoGuideConfirm() {
				uni.setStorageSync('loginFirst', '0');
				this.userInfoGuide = false
				uni.navigateTo({
					url: '/pages/tabbar/userCenter/userInfo'
				})
			},
			userInfoGuideCancel() {
				this.userInfoGuide = false
				uni.setStorageSync('loginFirst', '0');
			},
			checkAuth() {
				if (!this.checkInfo()) return
				/**
				 * 1、首次下载使用扫码功能，先给出自定义提示，再调用扫码
				 * 2、用户允许:下次扫码直接扫
				 * 3、用户不允许：给出自定义提示
				 */
				const notFirstInScan = uni.getStorageSync('notFirstInScan')
				if (!notFirstInScan) { // 首次登录
					this.showCameraTip()
					return
				}

				uni.getSystemInfo({
					success: (res) => {
						let type = res.osName.toLowerCase()
						if (type === 'ios') {
							let iosAuth = permision.judgeIosPermission("camera")
							if (iosAuth) {
								this.scanFn()
							} else {
								this.showCameraTip()
							}
						} else if (type === 'android') {
							this.requestAndroidPermission('android.permission.CAMERA')
						}
					}
				});
			},
			// Android授权
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID)
				var strStatus
				if (result == 1) {
					strStatus = "已获得授权"
					this.scanFn()
				} else if (result == 0) {
					strStatus = "未获得授权"
					this.showCameraTip()
				} else {
					strStatus = "被永久拒绝权限"
					this.showCameraTip()
				}
				console.log('strStatus')
			},
			scanFn() {
				const that = this
				uni.scanCode({
					success: (res) => {
						// 扫码成功回调
						console.log('扫码结果: ', JSON.stringify(res), res.result.includes('拼词之星三天体验卡'));
						// const content = res.result.includes('page.fengyongtech.com/#/qrcode?no=') ? res.result.split('page.fengyongtech.com/#/qrcode?no=')[1] : ''
						if (!res.result.includes('qrcode') &&
							!res.result.includes('拼词之星三天体验卡') &&
							!res.result.includes('dev.spbcn.org/qrcode')) return uni.showToast({
							title: '此码无效',
							icon: 'error'
						})
						var content = "";
						if (res.result.includes('qrcode?no=')) { //扫码解锁
							content = res.result.split('qrcode?no=')[1]
							console.log("content=============")
							console.log(content)
							that.openProduct(content)
						} else if (res.result.includes('拼词之星三天体验卡')) {
							that.openProduct('拼词之星三天体验卡')
						} else if (res.result.includes('qrcode?loginCodeStr=')) { // 扫码授权登录
							content = res.result.split('?loginCodeStr=')[1]
							that.AuthorizationLogin(content);
						}
					},
					fail: (err) => {
						// 扫码失败回调
						console.error('扫码失败: ', err);
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},
			// 授权登录
			AuthorizationLogin(content) {
				console.log('content____________', content);
				uni.navigateTo({
					url: '/pages/tabbar/home/autoLoginView?content=' + content
				})
			},
			confirmFn() {
				this.show = false
			},

			showCodeFn() {
				this.showCodePop = true
			},
			codeConfirm(code) {
				this.openProduct(code)
			},
			codeCancel() {
				this.showCodePop = false
			},

			openProduct(content) {
				var that = this;
				if (content == '') {
					that.msg = '兑换码不能为空！！'
					that.show = true;
					return false;
				}
				that.$http.scanQr({
					content
				}).then(res => {
					console.log('111111', res)
					that.showCodePop = false
					if (res.code === 200) {
						that.msg = '已开通' + res.data.name
						that.show = true
					} else {
						that.msg = res.msg
						that.show = true
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 1000;

		.fixed-content {
			padding: 0 24rpx;

			&.bg-b {
				background: linear-gradient(to bottom, #130e00 0%, #373632 100%);
			}

			.bar-content {
				display: flex;
				align-items: center;

				.nav-left {
					width: 18px;
					height: 18px;
					margin-right: 10px;
					margin-top: 20px;
					transform: translateY(-50%);
				}
			}
		}
	}

	.search-flex {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.search-area {
		// width: 70vw;
		flex: 1;
		height: 32px;
		background: #fff8e1;
		border-radius: 32px;
		box-sizing: border-box;
		padding-left: 8px;
		padding-right: 2px;
	}

	.operate-area {
		text-align: right;
		// width: 90px;
	}

	.opt-btn {
		width: 32px;
		height: 32px;
		margin-left: 10px;
	}

	.search-icon {
		width: 24px;
		height: 24px;
	}

	.search-area {
		display: flex;
		align-items: center;
	}

	.search-input {
		border: none;
	}

	.search-btn {
		width: 60px;
		height: 28px;
		border-radius: 28px;
		background: linear-gradient(-45deg, #373632 0%, #130E00 100%);
		color: #fff;
		font-weight: bold;
		border: none;
		text-align: center;
		line-height: 28px;
		font-size: 14px;
	}

	.item {
		height: 42px;
		line-height: 42px;
		padding: 0 12px;
		font-size: 14px;
		border-bottom: 1px solid #e3ddc9;
	}

	.default {
		color: #8a8787;
		font-size: 14px;
		text-align: center;
		height: 42px;
		line-height: 42px;
	}
</style>